package service

import (
	"awesomeProject/app/model"
	"awesomeProject/app/request"
	"awesomeProject/app/response"
	"awesomeProject/global"
	"awesomeProject/util"
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
	"regexp"
	"time"
)

type WareHorseSrv struct{}

func (a WareHorseSrv) Statistics(req request.Statistics) response.Resp {
	statistics := map[string]interface{}{
		"transMark":   "否",
		"lastTransAt": "--",
		"transTimes":  "0",
	}
	now := time.Now()
	today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local) // 获取当前时间
	timestamp := today.AddDate(0, 0, -7).Unix()
	fmt.Println(timestamp)
	filter := bson.D{
		bson.E{Key: "shopId", Value: req.ShopId},
		bson.E{Key: "title", Value: "高缺货ODR店铺管控"},
		bson.E{Key: "receivedTime", Value: bson.M{"$gte": timestamp}},
	}
	findOneOptions := options.FindOneOptions{}
	findOneOptions.SetSort(bson.M{"receivedTime": -1})
	var message model.OfficialMessage
	err := global.MongoDB.Collection("official_message").FindOne(context.TODO(), filter, &findOneOptions).Decode(&message)
	if err != nil {
		if err.Error() == "mongo: no documents in result" {
			return response.OK.WithData(statistics)
		}
		return response.ErrQuery.SetMsg(err.Error())
	}

	msgContent := fmt.Sprintf("%v", message.Content)
	re := regexp.MustCompile("全店已切为实库销售") // 匹配规则
	if len(re.FindAllString(msgContent, -1)) == 0 {
		statistics["transMark"] = "否"
	} else {
		statistics["transMark"] = "是"
		receivedTime := util.GetInterfaceToInt(message.ReceivedTime)
		statistics["lastTransAt"] = util.UnixToStr(int64(receivedTime), "2006-01-02 15:04:05")
		re = regexp.MustCompile("近60天受限已达(.*?)次") // 匹配规则
		matchArr := re.FindStringSubmatch(msgContent)
		if len(matchArr) == 0 {
			statistics["transTimes"] = 0
		} else {
			transTimes := matchArr[len(matchArr)-1]
			statistics["transTimes"] = transTimes
		}
	}

	return response.OK.WithData(statistics)
}
